<?php
declare (strict_types=1);

namespace addons\V4\admin\model;

use addons\Target\facade\Target;
use app\common\model\Area;
use app\common\model\Base;
use app\common\model\Express;
use app\common\model\Logs;
use app\common\model\Relation;
use app\common\model\User;
use think\facade\Event;

class Order extends Base
{
    protected $name = 'addons_mall_order';

    protected $type = [
        'post_time'    => 'timestamp',
        'pay_time'     => 'timestamp',
        'receipt_time' => 'timestamp',
        'release_time' => 'timestamp',
    ];

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,photo,mobile,level_id');
    }

    public function express()
    {
        return $this->hasOne(Express::class, 'id', 'express_id')->field('id,title');
    }

    public function p()
    {
        return $this->hasOne(Area::class, 'code', 'province')->field('code,province as title');
    }

    public function c()
    {
        return $this->hasOne(Area::class, 'code', 'city')->field('code,city as title');
    }

    public function d()
    {
        return $this->hasOne(Area::class, 'code', 'district')->field('code,district as title');
    }

    public function productsField()
    {
        return $this->hasMany(OrderProduct::class, 'order_id')
            ->field('id,order_id,pid,title,num,sku_name,vip_price,icon');
    }

    public function getPayWayAttr($value)
    {
        return get_pay_way($value);
    }

    public function getStatusAttr($value)
    {
        return self::getOrderStatus($value);
    }

    public static function getOrderStatus($value, $type = 1)
    {
        $status = [1 => '待付款', 2 => '待发货', 3 => '待收货', 4 => '已完成', 7 => '已取消'];
        return $type == 1 ? $status[$value] : $status;
    }

    public static function getTakeOverTableList($that, $param, $filed = '*', $count = 0)
    {
        try {
            foreach ($that as &$v) {
                foreach ($v->productsField as $item) {
                    $v->product .= '<div class="products">
<img class="openShowImg" data-value="' . $item['icon'] . '" src="' . $item['icon'] . '"/>' . $item['title'] . '';
                    if ($item['sku_name']) {
                        $v->product .= '<span style="color: #64B23A;font-weight: bold;margin-left: 5px">规格：' . $item['sku_name'] . '</span>';
                    }
                    $v->product .= '<span style="color: red;font-weight: bold;margin-left: 5px">数量：' . $item['num'] . "</span></div>";
                }
                $v->statusRaw = $v->getData('status');
            }
            return ['code' => 0, 'data' => $that, 'count' => $count];
        } catch (\Exception $e) {
            return [];
        }
    }

    /**
     * @param $param -- 提交的参数
     * @param $admin -- 后台当前登录管理员
     * @return array
     * 原点 2022年1月8日16:45:49 后台发货订单
     */
    public static function deliver($param, $admin, $business = '')
    {

        try {
            $info = parent::find($param['id']);
            if ($info->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到相关订单'];
            }
            $status = $info->status;
            $info->express_id = $param['express_id'];
            $info->express_code = $param['express_code'];
            $info->receiver = $param['receiver'];
            $info->receiver_tel = $param['receiver_tel'];
            $info->province = $param['province'];
            $info->city = $param['city'];
            $info->district = $param['district'];
            $info->address_details = $param['address_details'];
            $info->post_remark = $param['post_remark'];
            $info->post_time = time();

            $info->status = 3;
            $res = $info->save();
            if ($res !== true) {
                return ['code' => -1, 'msg' => '发货失败'];
            }
            if ($status < 3) {
                $msg = '订单发货，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
                $m = '已发货';
            } else {
                $msg = '修改了发货信息，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
                $m = '已修改';
            }
            Logs::adds($msg, $admin->id, $admin->admin_name);
            return ['code' => 1, 'msg' => $m];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //静态释放
    public static function release()
    {
        try {
           $list = Order::where(['order_type'=>1,'is_release'=>0,'pay_state'=>2,'delete_time'=>0])->column('id');
           $static = cache('system')['static'];
           foreach ($list as $k=>$v)
           {
               $order = Order::find($v);
               $release = bcmul((string)$static,(string)$order->real_amount,2);
               if($order->release + $release>$order->green)
               {
                   $release = $order->green - $order->release;
                   $upd['is_release'] = 1;
                   $upd['release_time'] = time();
                   Order::update($upd,['id'=>$order->id]);
               }
               if($release>0) {
                   Order::where('id', $order->id)->inc('release', floatval($release))->update();
                   Target::Account()->basics($order->uid, 'reward', $release, '静态释放', '+')
                       ->createBonus($order->uid, 1);
                   Event::trigger('Statistics', ['key' => 'expend', 'value' => $release]);
               }
               $user = User::find($order->uid);
               if($user->parent_id)
               {
                   Order::commission($user->parent_id,$order->uid,$release);//销售提成
                   Relation::teamBonus($user->id,$release); //团队销售提成
               }
           }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //销售提成
    public static function commission($p_uid,$uid,$amount)
    {
        try {
            $num = User::where(['parent_id'=>$p_uid,'is_active'=>2])->count();
            if($num)
            {
                if ($num >= 3) {
                    $num = 3;
                }
                $commission = 'commission_' . $num;
                $commissions = cache('system')[$commission];
                $release = bcmul((string)$amount, (string)$commissions, 2);
                $residue = 0;
                while ($order = Order::where(['uid'=>$p_uid,'order_type'=>1,'is_release'=>0,'pay_state'=>2,'delete_time'=>0])->order('id','asc')->find())
                {
                    if($order)
                    {
                        $release = $release - $residue;
                        if($order->release + $release>=$order->green)
                        {
                            $release = $order->green - $order->release;
                            $upd['is_release'] = 1;
                            $upd['release_time'] = time();
                            Order::update($upd,['id'=>$order->id]);
                            if($release>0) {
                                Order::where('id', $order->id)->inc('release', floatval($release))->update();
                                Target::Account()->basics($order->uid, 'reward', $release, '销售提成', '+')
                                    ->createBonus($uid, 2);
                                Event::trigger('Statistics', ['key' => 'expend', 'value' => $release]);
                            }
                            $residue += $release;
                        }else{
                            if($release>0) {
                                Order::where('id', $order->id)->inc('release', floatval($release))->update();
                                Target::Account()->basics($order->uid, 'reward', $release, '销售提成', '+')
                                    ->createBonus($uid, 2);
                                Event::trigger('Statistics', ['key' => 'expend', 'value' => $release]);
                            }
                            break;
                        }

                    }
                }
            }


        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

}
